package com.rzico.sbl.ui.order

import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import androidx.lifecycle.lifecycleScope
import com.jeremyliao.liveeventbus.utils.observe
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityOrderBinding
import com.rzico.sbl.model.BaseUrl
import com.rzico.sbl.model.OrderFooter
import com.rzico.sbl.model.OrderGoods
import com.rzico.sbl.model.OrderHeader
import com.rzico.sbl.other.privacyStatus
import com.rzico.sbl.other.showPriceDialog
import com.rzico.sbl.other.userRole
import com.rzico.sbl.viewmodel.OrderViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.*
import com.xinnuo.common.listener.onTabSelectedListener
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.bindLifeCycle
import com.xinnuo.common_ui.utils.setEmptyImage
import com.xinnuo.common_ui.utils.showHintDialog
import com.xinnuo.common_ui.utils.subscribeBySuccess
import com.xinnuo.slimadapter.SlimAdapter
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject

class OrderActivity : BaseActivity(R.layout.activity_order) {

    private val mBinding by lazy { ActivityOrderBinding.bind(getRootView()) }
    private var mState = ""
    private var mKeyWord = ""

    override fun getViewModel() = get<OrderViewModel>()

    override fun initData() {
        setToolbarVisibility(isVisible = false)

        initTabLayout()
        initLayout()
        initSearch()
    }

    private fun initTabLayout() {
        val index = intent.getIntExtra("index", 0)

        mBinding
            .orderTab
            .apply {
                onTabSelectedListener {
                    onTabSelected {
                        it?.let {
                            mState = when (it.position) {
                                1 -> "unpaid"
                                2 -> "unshipped"
                                3 -> "shipped"
                                4 -> "refunding"
                                5 -> "completed"
                                else -> ""
                            }

                            mBinding.apply {
                                (it.position == 2)
                                    .conditionElse(
                                        actionTrue = {
                                            orderVisual.visibleAnimation()
                                        },
                                        actionFalse = {
                                            orderVisual.goneAnimation()
                                        }
                                    )
                            }

                            getViewModel().cancelRequest()
                            getViewModel().delay { updateList() }
                        }
                    }
                }

                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "全部"
                    },
                    index == 0
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待付款"
                    },
                    index == 1
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待发货"
                    },
                    index == 2
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已发货"
                    },
                    index == 3
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "待退款"
                    },
                    index == 4
                )
                addTab(
                    newTab().apply {
                        setCustomView(R.layout.tablayout_item_custom)
                        customView?.find<TextView>(R.id.item_tab_title)?.text = "已完成"
                    },
                    index == 5
                )
            }
    }

    private fun initLayout() {
        mBinding
            .listLayout
            .apply {
                emptyLayout.also {
                    it.emptyImg.setEmptyImage(
                        resId = R.mipmap.icon_order_no,
                        dpSize = 100f
                    )
                    it.emptyHint.text = "暂无相关订单信息！"
                }

                recycleList.also { layout ->
                    layout.loadLinear(
                        refresh = swipeRefresh,
                        onRefresh = {
                            orderCount()
                            getData(0)
                        },
                        onLoad = {
                            isLoadingMore
                                .conditionFalse {
                                    isLoadingMore = true
                                    getData(pageNum)
                                }
                        }
                    )

                    mAdapter = SlimAdapter.creator()
                        .register<OrderHeader>(R.layout.item_order_list_title) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_time, bean.hint + bean.time)
                                text(R.id.item_order_status, bean.status_hint)

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .register<OrderGoods>(R.layout.item_order_list_content) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_type, "规格：${bean.spec.orEmpty()}")
                                text(R.id.item_order_price, "单价：${bean.price.formatDecimal()}元")
                                text(R.id.item_order_num, "x${bean.quantity}")

                                visibility(
                                    R.id.item_order_img_label,
                                    visibleValue { bean.first }
                                )

                                with<ImageView>(R.id.item_order_img) {
                                    it.loadImage(bean.thumbnail)
                                }

                                with<ImageView>(R.id.item_order_img_type) {
                                    when (bean.methodDescr) {
                                        "offline" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order03)
                                        }

                                        "eleme", "elemengc" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order04)
                                        }

                                        "meituan" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order05)
                                        }

                                        "nongfu" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order06)
                                        }

                                        "jd" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order10)
                                        }

                                        "taobao" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order11)
                                        }

                                        "pinduoduo" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order12)
                                        }

                                        "dummy" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order22)
                                        }

                                        "ali" -> {
                                            it.visible()
                                            it.setImageResource(R.mipmap.icon_order26)
                                        }

                                        else -> it.gone()
                                    }
                                }

                                with<ImageView>(R.id.item_order_img_status) {
                                    it.gone = bean.hopeDate.isEmpty() && bean.reminderDate.isEmpty()

                                    bean.hopeDate.notEmpty {
                                        it.setImageResource(
                                            conditionIf(
                                                bean.fast,
                                                R.mipmap.icon_order07,
                                                R.mipmap.icon_order02
                                            )
                                        )
                                    }

                                    bean.reminderDate.notEmpty {
                                        it.setImageResource(R.mipmap.icon_order24)
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .register<OrderFooter>(R.layout.item_order_list_foot) { jector, bean, _ ->
                            jector.apply {
                                text(R.id.item_order_count, bean.total_num)
                                text(R.id.item_order_total, bean.amount.formatDecimal())
                                text(R.id.item_order_total_hint, bean.amountHint)
                                text(R.id.item_order_name, bean.name)
                                text(R.id.item_order_shop, bean.meituanShopName)
                                text(
                                    R.id.item_order_phone,
                                    when {
                                        userRole in "1,2"
                                                || privacyStatus == "off" -> bean.phone

                                        else -> bean.phone.phoneReplaceWithStar()
                                    }
                                )
                                text(R.id.item_order_addr, bean.address)
                                text(R.id.item_order_yu, bean.estimateDate)
                                text(R.id.item_order_done, bean.deliveryDate)
                                text(R.id.item_order_cmemo, bean.cardMemo)
                                text(R.id.item_order_bmemo, bean.memo)

                                getView<View>(R.id.item_order_shop_ll)
                                    .isGone = bean.meituanShopName.isEmpty()
                                getView<View>(R.id.item_order_yu_ll).isVisible =
                                    bean.deliveryDate.isEmpty() && bean.estimateDate.isNotEmpty()
                                getView<View>(R.id.item_order_done_ll)
                                    .isGone = bean.deliveryDate.isEmpty()
                                getView<View>(R.id.item_order_cmemo_ll)
                                    .isGone = bean.cardMemo.isEmpty()
                                getView<View>(R.id.item_order_bmemo_ll)
                                    .isGone = bean.memo.isEmpty()

                                with<TextView>(R.id.item_order_pei) { tv ->
                                    tv.text =
                                        "配送员：${bean.adminName}${bean.adminPhone.ifNotEmpty { " - $it" }}"
                                    tv.isGone = bean.adminName.isEmpty()
                                }

                                with<TextView>(R.id.item_order_btn1) {
                                    it.text = bean.hint_btn1
                                    it.isGone = bean.hint_btn1.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" ->
                                                startActivityEx<OrderConfirmActivity>(
                                                    "amount" to bean.amount.formatDecimal(),
                                                    "orderSn" to bean.orderSN,
                                                    "time" to bean.createDate,
                                                    "index" to bean.position
                                                )

                                            "unshipped" ->
                                                startActivityEx<OrderShipActivity>(
                                                    "orderSn" to bean.orderSN,
                                                    "index" to bean.position
                                                )

                                            "shipped" ->
                                                if (bean.isShipping) {
                                                    startActivityEx<OrderCancelActivity>(
                                                        "orderSn" to bean.orderSN,
                                                        "shippingSn" to bean.shippingSn,
                                                        "index" to bean.position
                                                    )
                                                } else refuseOrder(bean.orderSN, bean.position)

                                            "refunding", "returning" ->
                                                refundConfirm(bean.orderSN, bean.position)

                                            "completed" -> refundOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn2) {
                                    it.text = bean.hint_btn2
                                    it.isGone = bean.hint_btn2.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> updatePrice(
                                                bean.orderSN,
                                                bean.amount,
                                                bean.position
                                            )

                                            "unshipped" -> refundOrder(bean.orderSN, bean.position)
                                            "shipped" ->
                                                startActivityEx<DeliverSendActivity>(
                                                    "mode" to "shipped",
                                                    "orderSn" to bean.orderSN,
                                                    "shippingSn" to bean.shippingSn,
                                                    "index" to bean.position
                                                )

                                            "refunding", "returning" ->
                                                revokeOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                with<TextView>(R.id.item_order_btn3) {
                                    it.text = bean.hint_btn3
                                    it.isGone = bean.hint_btn3.isEmpty()

                                    it.oneClick {
                                        when (bean.status) {
                                            "unpaid" -> cancelOrder(bean.orderSN, bean.position)
                                            "unshipped" -> throwOrder(bean.orderSN, bean.position)
                                        }
                                    }
                                }

                                clicked {
                                    startActivityEx<OrderDetailActivity>(
                                        "orderSn" to bean.orderSN,
                                        "shippingSn" to bean.shippingSn,
                                        "index" to bean.position
                                    )
                                }
                            }
                        }
                        .attachTo(layout)
                }
            }
    }

    private fun initSearch() {
        mBinding
            .searchLayout
            .apply {
                searchEdit.hint = "请输入收货人、电话、地址"
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入收货人、电话、地址")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入收货人、电话、地址")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding
            .apply {
                orderBatch.oneClick { startActivityEx<OrderBatchActivity>() }

                orderVisual.oneClick { startActivityEx<OrderShipMapActivity>() }

                orderWarn.oneClick { startActivityEx<OrderWarnActivity>() }

                // 观察超时订单数量
                getViewModel()
                    .mCountAllEvent
                    .observe(getLifecycleOwner()) { value ->
                        if (value.intValue > 0) {
                            orderWarn.bringToFront()
                            orderWarn.visibleAnimation(
                                onEnd = {
                                    orderWarnHint.setBadgeCount(value)
                                }
                            )
                        } else {
                            orderWarn.goneAnimation(
                                onEnd = {
                                    orderWarnHint.setBadgeCount(0)
                                }
                            )
                        }
                    }
            }

        // 观察超时订单页面操作
        observe<String>("orderWarn") {
            getViewModel()
                .delay { updateList() }
        }

        // 观察订单按钮操作
        observe<String>("orderList") {
            getViewModel()
                .delay { updateList() }
        }
    }

    /**
     * 订单改价
     */
    private fun updatePrice(orderSN: String, amount: String, index: Int) {
        showPriceDialog(
            title = "订单改价",
            default = amount,
            onSure = { value ->
                getViewModel()
                    .updateOrder(orderSN, value)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("订单改价成功！")

                            val item = mList.find {
                                it is OrderFooter
                                        && it.position == index
                            } as OrderFooter

                            item.amount = value

                            mAdapter.notifyDataSetChanged()
                        }
                    )
            }
        )
    }

    /**
     * 取消订单
     */
    private fun cancelOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "取消订单",
            hint = "确定要取消订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderCancel, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("取消订单成功！")

                            mList.removeAll {
                                (it is OrderHeader && it.position == index)
                                        || (it is OrderGoods && it.position == index)
                                        || (it is OrderFooter && it.position == index)
                            }

                            mAdapter.notifyDataSetChanged()

                            mBinding.listLayout
                                .emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }
                    )
            }
        )
    }

    /**
     * 抛单
     */
    private fun throwOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "抛单",
            hint = "确定要抛出订单吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderThrow, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("抛单成功！")

                            operateDone("shipped", index)
                        }
                    )
            }
        )
    }

    /**
     * 申请退款
     */
    private fun refundOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 申请退货退款
     */
    private fun refuseOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "退货退款",
            hint = "确定要退货退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderReturn, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("退货退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 确认退款
     */
    private fun refundConfirm(orderSN: String, index: Int) {
        showHintDialog(
            title = "确认退款",
            hint = "确定要同意退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderRefund, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("确认退款成功！")

                            operateDone("returned", index)
                        }
                    )
            }
        )
    }

    /**
     * 撤销退款
     */
    private fun revokeOrder(orderSN: String, index: Int) {
        showHintDialog(
            title = "撤销退款",
            hint = "确定要撤销退款吗？",
            onSure = {
                getViewModel()
                    .operateOrder(BaseUrl.orderBack, orderSN)
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeBySuccess(
                        event = getViewModel(),
                        onSuccess = {
                            showToast("撤销退款成功！")

                            operateDone("unshipped", index)
                        }
                    )
            }
        )
    }

    /**
     * 点击按钮完成后的操作
     */
    private fun operateDone(
        flag: String,
        index: Int,
        extra: String = ""
    ) {
        if (mState.isNotEmpty() && mState != "completed") {
            mList.removeAll {
                (it is OrderHeader && it.position == index)
                        || (it is OrderGoods && it.position == index)
                        || (it is OrderFooter && it.position == index)
            }

            mAdapter.notifyDataSetChanged()

            mBinding.listLayout
                .emptyLayout
                .emptyView
                .apply { if (mList.isEmpty()) visible() else gone() }
        } else {
            val itemHeader = mList.find {
                it is OrderHeader && it.position == index
            } as OrderHeader

            val itemFooter = mList.find {
                it is OrderFooter && it.position == index
            } as OrderFooter

            when (flag) {
                "unshipped" -> {
                    itemHeader.status_hint = "待发货"
                    itemFooter.status = flag
                    itemFooter.hint_btn1 = "发货"
                    itemFooter.hint_btn2 = if (userRole == "1") "退款" else ""
                    itemFooter.hint_btn3 = if (itemFooter.allowRob) "抛单" else ""
                }

                "shipped" -> {
                    itemHeader.status_hint = "已发货"
                    itemFooter.status = flag
                    itemFooter.adminName = extra
                    itemFooter.hint_btn1 = if (userRole == "1") "退货退款" else ""
                    itemFooter.hint_btn2 = "转派"
                    itemFooter.hint_btn3 = ""
                }

                "returned" -> {
                    itemHeader.status_hint = "已退款"
                    itemFooter.status = flag
                    itemFooter.hint_btn1 = ""
                    itemFooter.hint_btn2 = ""
                    itemFooter.hint_btn3 = ""
                }

                "review" -> {
                    itemHeader.status_hint = "待评价"
                    itemFooter.status = flag
                    itemFooter.hint_btn1 = ""
                    itemFooter.hint_btn2 = ""
                    itemFooter.hint_btn3 = ""
                }
            }

            mAdapter.notifyDataSetChanged()
        }
    }

    /**
     * 更新自定义Tab数量
     */
    private fun orderCount() {
        getViewModel()
            .orderCount()
            .bindLifeCycle(getLifecycleOwner())
            .subscribeBySuccess(
                event = getViewModel(),
                onSuccess = {
                    val obj = JSONObject(it)
                    getViewModel()
                        .updateNum(
                            obj.optNotNull("unpaid"),
                            obj.optNotNull("unshipped"),
                            obj.optNotNull("shipped"),
                            obj.optNotNull("refund"),
                            mBinding.orderTab
                        )
                }
            )
    }

    /**
     * 获取列表数据
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .orderList(
                page = index,
                state = mState,
                roleId = userRole,
                keyWord = mKeyWord,
                onSuccess = {
                    mList.apply {
                        if (index == 0) {
                            clear()
                            pageNum = 0
                        }
                        addItems(it)
                        it.notEmpty { pageNum++ }
                    }

                    mAdapter.setDataList(mList)
                },
                onFinally = {
                    isLoadingMore = false

                    mBinding
                        .listLayout
                        .apply {
                            swipeRefresh.isRefreshing = false

                            emptyLayout
                                .emptyView
                                .isVisible = mList.isEmpty()
                        }

                    lifecycleScope.launch {
                        delay(300)
                        getViewModel().warnCount()
                    }
                }
            )
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            clear()
            mAdapter.notifyDataSetChanged()
        }

        orderCount()
        getData(0)
    }

}